package encaps.action;

import encaps.entities.Grant;
import encaps.entities.User;
import encaps.entities.UserLocal;
import encaps.entities.UserLocalHome;
import encaps.logging.JMSUtil;
import encaps.logging.Log;
import encaps.resources.Labels;
import encaps.security.RoleManager;
import encaps.utils.DataAccessException;
import encaps.utils.EntityUtil;
import encaps.utils.InitializationException;
import encaps.utils.XMLHelper;
import java.util.Date;
import javax.ejb.FinderException;
import javax.naming.NamingException;
import org.jdom.Element;

public class EditProfileAction extends Action {

    public static final String EDIT_PROFILE = "editProfile";
    public static final String LOGIN = "login";
    public static final String OLD_PASSWORD = "oldpass";
    public static final String NEW_PASSWORD = "newpass";
    public static final String PICTURE = "pic";
    public static final String INFO = "info";
    public static final String EMAIL = "email";
    public static final String CONTACTS = "contacts";
    protected ActionContext actionContext;

    public EditProfileAction(ActionContext context, Grant requiredGrant) {
        this.actionContext = context;
        this.requiredGrant = requiredGrant;
    }

    @Override
    public Element execute() throws ActionExecutionException {
        try {
            UserLocalHome userHome = EntityUtil.getUserHome();
            UserLocal user = userHome.findByLogin(actionContext.getUserLogin());
            //Element userElement = XMLHelper.toXMLElement(user, Labels.getLabel(Labels.YOUR_PROFILE), true);

            JMSUtil.sendLogMessage(Log.UPDATE,
                    EntityUtil.getUserHome().findByLogin(actionContext.getUserLogin()).getID(),
                    actionContext.getUserLogin(), new Date(), User.TABLE_NAME,
                    user.getID(), user.getLogin());

            Element userElement = XMLHelper.toXMLElement(user, Labels.getLabel(Labels.EDIT_PROFILE), RoleManager.getRoleManager().getRole(actionContext.getUserRole()), true);
            //System.out.println(XMLHelper.toString(userElement));
            return userElement;
        } catch (InitializationException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        } catch (DataAccessException ex) {
            throw new ActionExecutionException(Labels.getLabel(Labels.CANNOT_EXECUTE_ACTION), ex);
        } catch (NamingException ex) {
            throw new ActionExecutionException("Cannot find UserLocalHome object", ex);
        } catch (FinderException ex) {
            throw new ActionExecutionException("User '" + actionContext.getUserLogin() + "' not found", ex);
        }
    }
}
